package com.shopping.exception;


import com.shopping.response.CodeMsg;
import com.shopping.response.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception ex){
        if(ex instanceof BindException){
            BindException bindException= (BindException) ex;
            List<ObjectError> allErrors = bindException.getAllErrors();
            ObjectError objectError = allErrors.get(0);
            String msg=objectError.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.findArgs(msg));
        } else if(ex instanceof GlobalException){
            GlobalException globalException= (GlobalException) ex;
            return Result.error(globalException.getCodeMsg());
        }
        else{
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
